package com.sstir.doctor.exception;

import com.sstir.doctor.config.Contants;
import com.sstir.doctor.result.RespResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
//import org.springframework.web.servlet.NoHandlerFoundException;


@Slf4j
@RestControllerAdvice(basePackages = {"com.sstir.sxpt.controller", "com.sstir.sxpt.service.impl"})
public class GlobalHandlerException {

    /**
     * 业务异常
     *
     * @param e 异常
     * @return 异常结果
     */
    /*@ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public RespResult handleBusinessException(BaseException e) {
        log.error(e.getMessage(), e);

        return RespResult.badRequest(e.getResponseEnum().getCode(), e.getResponseEnum().getMessage());
    }*/

    /**
     * 未定义异常
     *
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public RespResult handleException(Exception e) {
        log.error(getExceptionMessage(e));
        e.printStackTrace();
        return RespResult.badRequest(Contants.FAIL_CODE, Contants.FAIL_MSG);
    }

    private String getExceptionMessage(Exception e) {
        StackTraceElement[] elements = e.getStackTrace();
        String message = StringUtils.EMPTY;
        if (elements.length > 0) {
            StackTraceElement element = elements[0];
            message = "方法" + element.getClassName() + "." + element.getMethodName() +
                    "的第" + element.getLineNumber() +
                    "行抛出异常：" + e.toString();
        }
        if (StringUtils.isBlank(message)) {
            message = e.toString();
        }
        return message;
    }


}
